﻿using BCCommon;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace TMSWorkflowAutoJob
{
    internal static class InjectionService
    {
        public static IServiceCollection AddServices(this IServiceCollection services)
        {
            InjectToServiceCollerction(services, new AssemblyName("BCService"));
            InjectToServiceCollerction(services, new AssemblyName("BCWorkflowEngine"));
            InjectToServiceCollerction(services, new AssemblyName("BCData"));
            InjectToServiceCollerction(services, new AssemblyName("BCCommon"));
            InjectToServiceCollerction(services, new AssemblyName("BCAMap"));
            InjectToServiceCollerction(services, new AssemblyName("BCMongoData"));

            return services;
        }

        private static void InjectToServiceCollerction(IServiceCollection service, AssemblyName assemblyName)
        {
            Type[] types = Assembly.Load(assemblyName).GetTypes();
            IEnumerable<Type> interfaceType = types.Where(p => p.GetTypeInfo().IsInterface);

            foreach (Type item in interfaceType)
            {
                if (item.GetTypeInfo().GetCustomAttribute<NonInjectionAttribute>() != null)
                {
                    continue;
                }

                try
                {
                    Type implementClass = types.Single(p => p.GetTypeInfo().ImplementedInterfaces.Contains(item));
                    service.Add(new ServiceDescriptor(serviceType: item, implementationType: implementClass, lifetime: ServiceLifetime.Transient));
                }
                catch (Exception)
                {
                    throw new Exception($"该 {item.Name} 实现可能存在问题");
                }
            }
        }

    }
}
